/*
 * Copyright (C) 2003, Velocityme Partnership
 * OrganisationSessionBean.java
 *
 * Created on 25 August 2003, 05:06
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDeltaItemTypeBean;
import com.velocityme.entity.ChangeDeltaTypeBean;
import com.velocityme.entity.PermissionBean;
import javax.ejb.*;
import javax.naming.*;
import java.util.*;
import com.velocityme.interfaces.*;
import com.velocityme.utility.InvalidKeyException;
import com.velocityme.utility.PermissionDeniedException;
import com.velocityme.valueobjects.*;
import java.rmi.RemoteException;

/**
 *
 * @author  Robert Crida Work
 * @ejb.bean
 *           type="Stateless"
 *           cmp-version="2.x"
 *           name="OrganisationSession"
 *           jndi-name="ejb/OrganisationSession"
 *           view-type="local"
 *           transaction-type="Container"
 * @ejb.transaction type="Required"
 *
 * @ejb.util generate="physical"
 */
public class OrganisationSessionBean implements SessionBean {
    
    private SessionContext m_context;
    
    private SearchSessionLocal m_searchSessionLocal;

    private PermissionLocal m_permissionOrganisationCreate;
    private PermissionLocal m_permissionOrganisationEdit;
    private PermissionLocal m_permissionNodeView;

    /**
     * If the user has permission to create a new Organisation in the specified 
     * parentnode then go ahead and create it and log an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_parentNode The node which will contain the new Organisation
     * @param p_organisationValue The value details for the Organisation part of the organisation
     *
     * @ejb.interface-method view-type="local"
     **/
    public OrganisationLocal createOrganisation(KeySessionLocal p_keyLocal,
                                                NodeLocal p_parentNodeLocal,
                                                com.velocityme.valueobjects.OrganisationValue p_organisationValue)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, p_parentNodeLocal).contains(m_permissionOrganisationCreate)) {
                DBObjectLocal dBObjectLocal = DBObjectUtil.getLocalHome().create();
                ContactableValue contactableValue = p_organisationValue.getContactableValue();
                contactableValue.setType("Organisation");
                contactableValue.getNodeValue().setFinalType("Organisation");
                NodeValue nodeValue = contactableValue.getNodeValue();
                nodeValue.setType("Contactable");
                NodeLocal nodeLocal = NodeUtil.getLocalHome().create(dBObjectLocal, nodeValue, p_parentNodeLocal);
                nodeValue.setNodeId(nodeLocal.getNodeId());
                ContactableSessionUtil.getLocalHome().create().calcContactDetailChanges(contactableValue, null);
                ContactableLocal contactableLocal = ContactableUtil.getLocalHome().create(nodeLocal, contactableValue);
                contactableValue.setContactableId(contactableLocal.getContactableId());
                OrganisationLocal organisationLocal = OrganisationUtil.getLocalHome().create(contactableLocal, p_organisationValue);
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.CREATE, p_keyLocal.getUserLocal(), dBObjectLocal);
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.PARENT_NODE, p_parentNodeLocal.getPathName());
                ContactableSessionUtil.getLocalHome().create().addContactDetailDeltas(changeDeltaLocal, contactableValue);
                return organisationLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to edit the organisation then do so and log the
     * changes with an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_organisation The Organisation object being edited
     * @param p_organisationValue The value details for the Organisation part of the organisation
     *
     * @ejb.interface-method view-type="local"
     **/
    public void editOrganisation(KeySessionLocal p_keyLocal,
                                 OrganisationLocal p_organisationLocal,
                                 com.velocityme.valueobjects.OrganisationValue p_organisationValue)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            ContactableLocal contactableLocal = p_organisationLocal.getContactableLocal();
            NodeLocal nodeLocal = contactableLocal.getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionOrganisationEdit)) {
                ContactableValue contactableValue = p_organisationValue.getContactableValue();
                NodeValue nodeValue = contactableValue.getNodeValue();
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.EDIT, p_keyLocal.getUserLocal(), nodeLocal.getDBObjectLocal());
                if (!nodeValue.getName().equals(nodeLocal.getName()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                if (!nodeValue.getDescription().equals(nodeLocal.getDescription()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                ContactableSessionUtil.getLocalHome().create().calcContactDetailChanges(contactableValue, contactableLocal.getContactDetailsLocal());
                ContactableSessionUtil.getLocalHome().create().addContactDetailDeltas(changeDeltaLocal, contactableValue);
                nodeLocal.setNodeValue(nodeValue);
                contactableLocal.setContactableValue(contactableValue);
                p_organisationLocal.setOrganisationValue(p_organisationValue);
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to access an organisation then return the local object.
     *
     * @param p_key User's security key
     * @param p_organisationPK The Organisation object to lookup
     *
     * @ejb.interface-method view-type="local"
     **/
    public OrganisationLocal getOrganisationLocal(KeySessionLocal p_keyLocal, 
                                                  OrganisationPK p_organisationPK)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            OrganisationLocal organisationLocal = OrganisationUtil.getLocalHome().findByPrimaryKey(p_organisationPK);
            NodeLocal nodeLocal = organisationLocal.getContactableLocal().getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionNodeView)) {
                return organisationLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * Get the full list of organisation value objects.
     *
     * @param p_key User's security key
     *
     * @ejb.interface-method view-type="local"
     **/
    public java.util.Collection getAllValueObjects(KeySessionLocal p_keyLocal) throws InvalidKeyException {
        Collection values = new java.util.ArrayList();
        try {
            if (p_keyLocal.isValid()) {
                Collection organisations = OrganisationUtil.getLocalHome().findAll();
                Iterator i = organisations.iterator();
                while(i.hasNext()) {
                    OrganisationLocal organisationLocal = (OrganisationLocal)i.next();
                    values.add(organisationLocal.getOrganisationValue());
                }
            }
            else
                throw new InvalidKeyException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
        return values;
    }
    
    /**
     * Create the Session Bean.
     * @throws CreateException 
     * @ejb:create-method view-type="remote"
     */
    public void ejbCreate() throws CreateException {
        try {
            m_searchSessionLocal = SearchSessionUtil.getLocalHome().create();
            m_permissionOrganisationCreate = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.ORGANISATION_CREATE)));
            m_permissionOrganisationEdit = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.ORGANISATION_EDIT)));
            m_permissionNodeView = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.NODE_VIEW)));
        }
        catch(NamingException e) {
            throw new CreateException(e.getMessage());
        }
        catch(FinderException e) {
            throw new CreateException(e.getMessage());
        }
    }

    public void ejbActivate() throws java.rmi.RemoteException {
    }
    
    public void ejbPassivate() throws java.rmi.RemoteException {
    }
    
    public void ejbRemove() throws java.rmi.RemoteException {
    }
    
    public void setSessionContext(javax.ejb.SessionContext sessionContext) throws java.rmi.RemoteException {
        m_context = sessionContext;
    }
    
}
